<template>
  <div id="exam">
    <div class="title">
      <span>试卷详情 / </span>
      <span>{{ examData.name }}</span>
    </div>

    <div class="wrapper">
      <ul class="top">
        <li class="example">{{ examData.name }}</li>
        <li><i class="iconfont icon-pen"></i></li>
        <li><i class="iconfont icon-share"></i></li>
        <li class="right">
          <div>
            <span class="count">总分</span>
            <span class="score">{{ examData.totalScore }}</span>
          </div>
        </li>
      </ul>

      <ul class="bottom">
        <li>开始时间 {{ examData.startTime?.slice(0, 10) }}</li>
        <li class="btn">{{ examData.type === 1 ? '正式考试' : '练习' }}</li>
        <li class="right">
          <el-button type="primary" @click="toAnswer(examData.id)">开始答题</el-button>
        </li>
      </ul>
    </div>

    <div class="content">
      <el-collapse v-model="activeName">
        <el-collapse-item name="0">
          <template v-slot:title>
            <div class="title">
              <span>{{ examData.name }}</span>
              <i class="header-icon el-icon-info"></i>
              <span class="time">{{ examData.totalScore }}分 / {{ examData.totalTime }}</span>
              <el-button type="primary" size="small">点击查看试题详情</el-button>
            </div>
          </template>

          <el-collapse class="inner">
            <el-collapse-item name="1" v-if="questions[1]?.length">
              <template v-slot:title>
                <div class="titlei">选择题 (共{{ count[1] }}题 共计{{ score[1] }}分)</div>
              </template>
              <div class="contenti">
                <ul class="question" v-for="(item, index) in questions[1]" :key="item.id">
                  <li>{{ index + 1 }}. {{ item.content }} ({{ item.score }}分)</li>
                </ul>
              </div>
            </el-collapse-item>

            <el-collapse-item name="0" v-if="questions[0]?.length">
              <template v-slot:title>
                <div class="titlei">填空题 (共{{ count[0] }}题 共计{{ score[0] }}分)</div>
              </template>
              <div class="contenti">
                <ul class="question" v-for="(item, index) in questions[0]" :key="item.id">
                  <li>{{ index + 1 }}. {{ item.content }} ({{ item.score }}分)</li>
                </ul>
              </div>
            </el-collapse-item>

            <el-collapse-item name="2" v-if="questions[2]?.length">
              <template v-slot:title>
                <div class="titlei">判断题 (共{{ count[2] }}题 共计{{ score[2] }}分)</div>
              </template>
              <div class="contenti">
                <ul class="question" v-for="(item, index) in questions[2]" :key="item.id">
                  <li>{{ index + 1 }}. {{ item.content }} ({{ item.score }}分)</li>
                </ul>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      examData: {},
      questions: { 0: [], 1: [], 2: [] },
      count: {},
      score: {},
      activeName: '0',
      questionIds: [],
    };
  },
  mounted() {
    this.loadExam();
  },
  methods: {
    loadExam() {
      const name = decodeURIComponent(this.$route.params.name);
      const courseId = this.$route.query.courseId;
      const examId = this.$route.query.examId;
      console.log('✅ 传入的课程ID:', courseId);
      if (!name) {
        this.$message.error('缺少考试名称参数');
        return;
      }

      this.$axios
        .get('/api/exam/page', {
          params: { pageNum: 1, pageSize: 100, name, courseId },
        })
        .then((res) => {
          if (res.data.code === 200) {
            const examList = res.data.data.records;
            const exam = examList.find((e) => e.name === name);

            if (!exam) {
              this.$message.error('未找到对应考试');
              return;
            }

            this.examData = exam;
            this.$cookies.set('examId', exam.id, '1h'); // ✅ 存入考试ID
            this.$cookies.set('paperId', exam.paperId, '1h');
            this.loadPaper(exam.paperId);
          }
        })
        .catch(() => {
          this.$message.error('考试信息加载失败');
        });
    },

    loadPaper(paperId) {
  if (!paperId) {
    this.$message.error('该考试未绑定试卷');
    return;
  }

  this.$axios.get(`/api/paper/id`, { params: { id: paperId } }).then((res) => {
    if (res.data.code !== 200) {
      this.$message.error('试卷加载失败');
      return;
    }

    const records = res.data.data.records || [];
    const grouped = { 0: [], 1: [], 2: [] };

    records.forEach((q) => {
      if (grouped.hasOwnProperty(q.type)) {
        grouped[q.type].push(q);
      }
    });

    this.questions = grouped;
    this.count = {};
    this.score = {};

    for (let type in grouped) {
      this.count[type] = grouped[type].length;
      this.score[type] = grouped[type].reduce((sum, q) => sum + (q.score || 0), 0);
    }

    // ✅ 按顺序提取题目ID并存入cookie
    this.questionIds = records.map((q) => q.id);
    this.$cookies.set('questionIds', this.questionIds, '1h');

    // ✅ 存入完整题目信息
    this.$cookies.set('questionList', records, '1h');
    console.log(this.$cookies.get('questionList'))
    console.log(this.$cookies.get('questionIds'))

    try {
      localStorage.setItem('questionList', JSON.stringify(records));
      console.log('✅ questionList 写入 localStorage 成功');
    } catch (e) {
      console.error('❌ 写入 localStorage 失败:', e);
      this.$message.error('浏览器存储失败，请检查空间');
    }
  });
},

    toAnswer(examId) {
      this.$router.push({
        path: '/answer',
        query: {
          examCode: examId,
          examID: examId,
          questionIds: this.questionIds.join(',')
        }
      });
    },
  },
};
</script>

<style scoped>
#exam {
  background: #eee;
  width: 980px;
  margin: 0 auto;
}
.title {
  margin: 20px;
  font-size: 22px;
  font-weight: bold;
}
.wrapper {
  background: #fff;
  padding: 10px;
}
.wrapper .top {
  display: flex;
  margin: 20px;
  align-items: center;
}
.wrapper .top .example {
  font-weight: bold;
  font-size: 20px;
}
.wrapper .top li i {
  margin-left: 20px;
  color: #88949b;
}
.right {
  margin-left: auto;
}
.right .count {
  margin-right: 60px;
  color: #fff;
  padding: 4px 10px;
  background: #88949b;
  border-radius: 4px 0 0 4px;
}
.right .score {
  position: absolute;
  left: 53px;
  top: -5px;
  padding: 1px 12px;
  font-size: 20px;
  color: #88949b;
  border: 1px dashed #88949b;
  border-left: none;
  border-radius: 0 4px 4px 0;
  font-weight: bold;
}
.right div {
  position: relative;
}
.bottom {
  display: flex;
  margin-left: 20px;
  align-items: center;
}
.bottom li {
  margin-right: 14px;
}
.btn {
  padding: 5px 10px;
  border: 1px solid #88949b;
  border-radius: 4px;
}
.content {
  margin-top: 20px;
  background: #fff;
}
.titlei {
  margin-left: 20px;
  font-size: 16px;
  font-weight: bold;
  color: #88949b;
}
.contenti .question {
  margin-left: 40px;
  font-size: 14px;
  color: #666;
}
</style>
